package com.zzb.projectfactory.framework.autodoc.document.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Charsets;
import com.zzb.projectfactory.framework.autodoc.bean.ConfigBean;
import com.zzb.projectfactory.framework.autodoc.bean.DocBean;
import com.zzb.projectfactory.framework.autodoc.bean.ParamBean;
import com.zzb.projectfactory.framework.autodoc.bean.ParamField;
import com.zzb.projectfactory.framework.autodoc.constant.ModuleType;
import com.zzb.projectfactory.framework.autodoc.document.AbstractCreateDocument;
import com.zzb.projectfactory.framework.autodoc.document.bean.*;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * 创建json文档
 * Created by zhangzhenbin on 2017/2/14.
 */
public class JsonCreateDocumentImpl implements AbstractCreateDocument {
    @Override
    public void create(List<DocBean> docBeanList, ConfigBean configBean) {
        JsonBean jsonBean = new JsonBean();
        jsonBean.setProjectName(configBean.getProjectName());
        Map<String, List<DocBean>> catalogMap = buildCatalog(docBeanList, configBean);

        Map<String, List<DocBean>> chapterMap = new TreeMap<>((o1, o2) -> ModuleType.getByName(o1).getIndex() > ModuleType.getByName(o2).getIndex() ? 1 : -1);
        for (Map.Entry<String, List<DocBean>> entry : catalogMap.entrySet()) {
            String key = entry.getKey();
            List<DocBean> valueList = entry.getValue();
            if (!valueList.isEmpty()) {
                chapterMap.put(key, valueList);
            }
        }
        System.out.println(JSON.toJSONString(chapterMap));

        List<ChapterBean> navData = new ArrayList<>();
        jsonBean.setNavData(navData);
        chapterMap.forEach((s1, docBeanList1) -> {
            ChapterBean  chapterBean = new ChapterBean();
            chapterBean.setLabel(s1);
            List<SectionBean> sectionChildren = new ArrayList<SectionBean>();
            chapterBean.setChildren(sectionChildren);
            docBeanList1.forEach(docBean -> {
                SectionBean section = new SectionBean();
                section.setLabel(docBean.getActionName());
                List<ListDataBean> listDataBeen = new ArrayList<ListDataBean>();
                section.setListData(listDataBeen);
                listDataBeen.add(new ListDataBean("请求地址",docBean.getActionUrl()));
                listDataBeen.add(new ListDataBean("接口开发人",docBean.getAuthor()));
                listDataBeen.add(new ListDataBean("创建时间",docBean.getCreateTime()));
                listDataBeen.add(new ListDataBean("请求方式",docBean.getReqMethod()));
                listDataBeen.add(new ListDataBean("请求类型",docBean.getReqType()));
                listDataBeen.add(new ListDataBean("版本",docBean.getVersion()));
                listDataBeen.add(new ListDataBean("是否已停用",docBean.isDeprecated()?"是":"否"));
                if(StringUtils.isNotBlank(docBean.getActionDesc()))
                    listDataBeen.add(new ListDataBean("描述",docBean.getActionDesc()));
                if(StringUtils.isNotBlank(docBean.getUpdateBy()))
                    listDataBeen.add(new ListDataBean("修改人",docBean.getUpdateBy()));
                if(StringUtils.isNotBlank(docBean.getUpdateTime()))
                    listDataBeen.add(new ListDataBean("修改时间",docBean.getUpdateTime()));
                if(StringUtils.isNotBlank(docBean.getUpdateVersion()))
                    listDataBeen.add(new ListDataBean("修改版本",docBean.getUpdateVersion()));

                final List<TableDataBean> requestTableData = new ArrayList<>();
                final List<TableDataBean> responseTableData = new ArrayList<>();
                section.setRequestTableData(requestTableData);
                section.setResponseTableData(responseTableData);

                //提交参数
                List<ParamField> params = docBean.getParams();
                params.forEach(paramField -> {
                    TableDataBean tableDataBean = new TableDataBean();
                    tableDataBean.setParamName(paramField.getName());
                    tableDataBean.setParamType(paramField.getType());
                    tableDataBean.setRemark(paramField.getNote());
                    tableDataBean.setRequired(paramField.isRequired()?"是":"否");
                    section.getRequestTableData().add(tableDataBean);
                });

                //返回参数
                ParamBean response = docBean.getResponse();

                section.getResponseTableData().addAll(getResponseTableDataBean(response,new ArrayList<>()));

                sectionChildren.add(section);
            });
            navData.add(chapterBean);
        });
        String json = JSON.toJSONString(jsonBean);
        String s = "let jsonData = " + json  + ";\nexport default jsonData;";
        System.out.println(json);
        String fileName = configBean.getFilePath() + configBean.getFileName() + ".js";
        File file = new File(fileName);
        try {
            FileUtils.write(file,s, Charsets.UTF_8,false);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    private static Map<String, List<DocBean>> buildCatalog(List<DocBean> beanList, ConfigBean configBean) {
        // 构建章节(list -> map)
        Map<String, List<DocBean>> tempMap = new HashMap<String, List<DocBean>>(50);
        for (DocBean bean : beanList) {
            List<DocBean> list = tempMap.get(bean.getModelName().trim());
            if (list == null) {
                list = new ArrayList<DocBean>();
                tempMap.put(bean.getModelName().trim(), list);
            }

            if (!configBean.isShowAllVersion()) {
                if (!bean.getVersion().equals(configBean.getCurrentVersion().getDes())) {
                    if (StringUtils.isNotBlank(bean.getUpdateVersion())) {
                        if (!bean.getUpdateVersion().equals(configBean.getCurrentVersion().getDes())) {
                            continue;
                        }
                    } else {
                        continue;
                    }
                }
            }

            if (!configBean.isShowDeprecated()) {
                if (bean.isDeprecated()) {
                    continue;
                }
                if (StringUtils.isNotBlank(bean.getStopVersion())) {
                    if (!bean.getStopVersion().equals(configBean.getCurrentVersion().getDes())) {
                        continue;
                    }
                }
            }
            list.add(bean);
        }
        return tempMap;
    }

    private List<TableDataBean> getResponseTableDataBean(ParamBean paramBean,List<TableDataBean> tableDataBeen){
        List<ParamField> params = paramBean.getParams();
        for (ParamField param : params) {
            TableDataBean tableDataBean = new TableDataBean();
            tableDataBean.setParamName(param.getName());
            tableDataBean.setParamType(param.getType());
            tableDataBean.setRemark(param.getNote());
            tableDataBean.setRequired(param.isRequired()?"是":"否");
            tableDataBeen.add(tableDataBean);
        }
        List<ParamBean> subBeans = paramBean.getSubBeans();
        for (ParamBean subBean : subBeans) {
            TableDataBean tableDataBean = new TableDataBean();
            tableDataBean.setRemark(subBean.getNote());
            tableDataBean.setParamName(subBean.getBeanName());
            tableDataBean.setParamType(subBean.getClassName());
            tableDataBean.setRequired(subBean.isRequired()?"是":"否");
            tableDataBean.setSubs(getResponseTableDataBean(subBean,new ArrayList<>()));
            tableDataBeen.add(tableDataBean);
        }
        return tableDataBeen;
    }
}
